import { CloseCircleOutlined } from '@ant-design/icons'
import { Select } from 'antd'
import { useEffect, useState } from 'react'

import AekButton from '@/components/AekButton'
import AekDrawer, { PromiseThen } from '@/components/AekDrawer'
import AekForm from '@/components/AekForm'
import { message } from '@/utils/antdHelper'

import { DATETIME_TYPE_ENUM, FIELD_TYPE_ENUM, REQUIRED_ENUM } from './enum'
import SelFieldsDrawer from './SelFieldsDrawer'

const request = async (url, params) => {
  const postOptions = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(params),
  }
  const response = await fetch(`http://127.0.0.1:9001/api/${url}`, postOptions)
  const { code, data, message: resMessage } = await response.json()
  if (code !== 0) {
    message.error(resMessage)
    return Promise.reject(resMessage)
  }
  return data
}

/**
 * 将蛇形命名的字符串转换为驼峰命名
 * @param {string} str - 要转换的蛇形命名的字符串
 * @returns {string} - 转换后的驼峰命名的字符串
 */
const snakeToCamel = str => {
  return str.replace(/_([a-z])/g, function (match, group) {
    return group.toUpperCase()
  })
}

/** 添加页面 */
const AddNewPage = () => {
  const [form] = AekForm.useForm()

  const [mySQLTables, setMySQLTables] = useState([])
  const [selTable, setSelTable] = useState()
  const [tableFullInfo, setTableFullInfo] = useState([])
  const [formFields, setFormFields] = useState([])
  const [searchFormFields, setSearchFormFields] = useState([])
  const [tableFields, setTableFields] = useState([])

  /**
   * 获取 MySQL 表名列表
   */
  const getMySQLTables = async () => {
    const params = {}
    const data = await request('getMySQLTables', params)
    setMySQLTables(data)
  }

  useEffect(() => {
    getMySQLTables()
  }, [])

  /**
   * 获取指定表的完整信息
   * @param {string} tableName - 要获取信息的表名
   */
  const getTableFullInfo = async tableName => {
    const params = {
      tableName,
    }
    const data = await request('getTableFullInfo', params)
    setTableFullInfo(data.columns)
    const excludeFields = [
      'id',
      'create_user_id',
      'create_user_name',
      'create_time',
      'update_user_id',
      'update_user_name',
      'update_time',
      'version',
      'deleted',
    ]
    const fields = data.columns.filter(item => !excludeFields.includes(item.COLUMN_NAME))
    setFormFields(fields)
    setSearchFormFields(fields)
    setTableFields(fields)
  }

  /**
   * 添加表单字段
   */
  const addFormFields = async () => {
    const selList = await SelFieldsDrawer.PromiseThen({
      tableFullInfo,
      selList: formFields,
    })
    setFormFields(selList)
  }

  /**
   * 添加搜索表单字段
   */
  const addSearchFormFields = async () => {
    const selList = await SelFieldsDrawer.PromiseThen({
      tableFullInfo,
      selList: searchFormFields,
    })
    setSearchFormFields(selList)
  }

  /**
   * 添加表格字段
   */
  const addTableFields = async () => {
    const selList = await SelFieldsDrawer.PromiseThen({
      tableFullInfo,
      selList: tableFields,
    })
    setTableFields(selList)
  }

  const onSelectTable = async tableName => {
    setFormFields([])
    setSearchFormFields([])
    setTableFields([])
    setSelTable(tableName)
    getTableFullInfo(tableName)
  }

  const formMap = [
    {
      key: 'formData',
      label: '表单项',
      fields: formFields,
      setFields: setFormFields,
      onclick: addFormFields,
    },
    {
      key: 'searchFormData',
      label: '搜索项',
      fields: searchFormFields,
      setFields: setSearchFormFields,
      onclick: addSearchFormFields,
    },
    {
      key: 'tableColumns',
      label: '列表项',
      fields: tableFields,
      setFields: setTableFields,
      onclick: addTableFields,
    },
  ]

  const onOk = async () => {
    const { searchFormData, tableColumns, formData, addPopupType, pageName, fileUrl } = await form.validateFields()
    const params = {
      namespace: snakeToCamel(selTable),
      formData: Object.keys(formData.field).map(key => ({
        field: formData.field[key],
        label: formData.label[key],
        type: formData.type?.[key],
        required: formData.required[key],
      })),
      searchFormData: Object.keys(searchFormData.field).map(key => ({
        field: searchFormData.field[key],
        label: searchFormData.label[key],
        type: searchFormData.type?.[key],
      })),
      tableColumns: Object.keys(tableColumns.field).map(key => ({
        field: tableColumns.field[key],
        label: tableColumns.label[key],
        type: tableColumns.type?.[key],
      })),
      addPopupType,
      pageName,
      fileUrl,
    }
    await request('createPage', params)
    message.success('创建成功')
    // setSearchFormFields([])
    // setTableFields([])
  }

  return (
    <AekDrawer title='添加页面' width={1200} onOk={onOk}>
      <div className='flex h-full flex-col'>
        <div>
          <span>表名：</span>
          <Select
            showSearch
            placeholder='请选择表名'
            className='w-300px'
            options={mySQLTables.map(item => ({ value: item, label: item }))}
            onSelect={onSelectTable}
          />
        </div>
        <div className='flex-grow-1 flex flex-col overflow-y-auto overflow-x-hidden'>
          {formMap.map(({ key, label, fields, setFields, onclick }) => (
            <div key={key} className='mt10px'>
              <AekButton type='primary' onClick={onclick}>
                编辑{label}
              </AekButton>
              <div>
                <AekForm
                  layout={['150px']}
                  form={form}
                  formData={fields.map(({ COLUMN_NAME, COLUMN_TYPE, COLUMN_COMMENT }, index) => ({
                    label: COLUMN_NAME,
                    component: [
                      {
                        field: [key, 'field', COLUMN_NAME],
                        formItemProps: {
                          initialValue: snakeToCamel(COLUMN_NAME),
                          rules: [{ required: true }],
                        },
                        component: { name: 'Input', props: { width: 150 } },
                      },
                      {
                        field: [key, 'label', COLUMN_NAME],
                        formItemProps: {
                          initialValue: COLUMN_COMMENT,
                          rules: [{ required: true }],
                        },
                        component: { name: 'Input', props: { width: 150 } },
                      },
                      {
                        exclude: key !== 'formData',
                        field: [key, 'required', COLUMN_NAME],
                        formItemProps: {
                          rules: [{ required: true }],
                          initialValue: REQUIRED_ENUM.TRUE,
                        },
                        component: { name: 'Select', props: { width: 150, options: REQUIRED_ENUM.options } },
                      },
                      {
                        exclude: COLUMN_TYPE !== FIELD_TYPE_ENUM.DATETIME,
                        field: [key, 'type', COLUMN_NAME],
                        formItemProps: {
                          rules: [{ required: true }],
                        },
                        component: { name: 'Select', props: { width: 150, options: DATETIME_TYPE_ENUM.options } },
                      },
                      {
                        component: (
                          <CloseCircleOutlined
                            className='ml10px c-del'
                            onClick={() => {
                              const newFields = [...fields]
                              newFields.splice(index, 1)
                              setFields(newFields)
                            }}
                          />
                        ),
                      },
                    ],
                  }))}
                />
              </div>
            </div>
          ))}
        </div>
        <div className='mt10px'>
          <AekForm
            form={form}
            formData={[
              {
                field: 'addPopupType',
                label: '新增框方式',
                formItemProps: {
                  rules: [{ required: true }],
                },
                component: {
                  name: 'Select',
                  props: {
                    options: [
                      { value: 'modal', label: 'modal' },
                      { value: 'drawer', label: 'drawer' },
                    ],
                  },
                },
              },
              {
                field: 'pageName',
                label: '页面名称',
                formItemProps: {
                  rules: [{ required: true }],
                },
                component: {
                  name: 'Input',
                },
              },
              {
                field: 'fileUrl',
                label: '页面路径',
                formItemProps: {
                  rules: [{ required: true }],
                },
                component: {
                  name: 'Select',
                  props: {
                    options: [
                      { value: 'pcs', label: 'pcs' },
                      { value: 'sys', label: 'sys' },
                    ],
                  },
                },
              },
            ]}
          />
        </div>
      </div>
    </AekDrawer>
  )
}

AddNewPage.PromiseThen = PromiseThen

export default AddNewPage
